package callnumber.gtdev5.com.photoVault.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import callnumber.gtdev5.com.photoVault.R;
import callnumber.gtdev5.com.photoVault.adapter.VideoImageAdapter;
import callnumber.gtdev5.com.photoVault.base.BaseActivity;
import callnumber.gtdev5.com.photoVault.bean.VideoFileBean;
import callnumber.gtdev5.com.photoVault.utils.DialogUtils;
import callnumber.gtdev5.com.photoVault.utils.FileSizeUtil;
import callnumber.gtdev5.com.photoVault.utils.ImageUtils;

public class VideoActivity extends BaseActivity {
    @BindView(R.id.rc_imag)
    RecyclerView rcImag;
    private VideoImageAdapter adapter;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.head_back)
    ImageView headBack;
    List<String> strings;
    private Dialog mWeiboDialog;
    private static final int COMPLETED = 0;
    int ids;
    List<Bitmap> str;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == COMPLETED) {
                GridLayoutManager manager = new GridLayoutManager(getApplicationContext(), 3);
                rcImag.setLayoutManager(manager);
                adapter.AddDatas(str);
                rcImag.setAdapter(adapter);
                DialogUtils.closeDialog(mWeiboDialog);
            }
        }
    };

    @Override
    protected int getLayouId() {
        return R.layout.activity_video;
    }

    List<VideoFileBean> newsList;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        ButterKnife.bind(this);
    }

    @Override
    protected void initDatas() {
        ids = getIntent().getIntExtra("ids", 0);
        mWeiboDialog = DialogUtils.createLoadingDialog(VideoActivity.this, "加载中...");
//        checkPermission();
        new WorkThread().start();
        button.setOnClickListener(v -> {

            String filePath = "/sdcard/encryption";
            File file = new File(filePath);
            if (file.exists()) {
                //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                double s = FileSizeUtil.getFileOrFilesSize(filePath, 3);
                double two = 5;
                String re = FileSizeUtil.getDouble(s, two);
                if (vip.isIsout() && re.equals("1")) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);
                    builder.setTitle("警告：");
                    builder.setMessage("内存已满，请前往首页开通会员！");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

                    builder.show();


                } else {
                    Intent intent = new Intent(VideoActivity.this, PhotoSelectActivity.class);
                    intent.putExtra(PhotoSelectActivity.IMAGE_NUM, 9);
                    startActivityForResult(intent, 0);
                }
            }
            if (!file.exists()) {
                //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                file.mkdirs();
            }

        });
        headBack.setOnClickListener(v -> finish());

    }

    public void getData() {
        newsList = new ArrayList<>();
        newsList = DataSupport.where("ids = ?", ids + "").find(VideoFileBean.class);
        adapter = new VideoImageAdapter(this, 20, null, newsList, new VideoImageAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(int position) {
                System.out.println("-------position1 = " + position);
                Intent intent = new Intent(VideoActivity.this, VideoPlayActivity.class);//
                intent.putExtra("list", (Serializable) newsList);
                intent.putExtra("position", position);
                intent.putExtra("ids", ids);
                startActivity(intent);
            }

        });

        if (newsList != null && !newsList.isEmpty()) {
            str = new ArrayList<>();
            strings = new ArrayList<>();
            for (VideoFileBean fileNameBean : newsList) {
                if (ImageUtils.fileIsExists(fileNameBean.getName())) {
                    String text = fileNameBean.getName();
                    ImageUtils.renameFile(fileNameBean.getName(), text);
                    Bitmap bitmap = null;//从路径加载出图片bitmap

                    try {
                        bitmap = Glide.with(getApplicationContext())
                                .asBitmap() //必须
                                .load(text)
                                .into(500, 500)
                                .get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                    strings.add(text);
                    str.add(bitmap);
                }

            }

        }

    }

    //工作线程
    private class WorkThread extends Thread {
        @Override
        public void run() {
            //......处理比较耗时的操作
            //处理完成后给handler发送消息
            getData();
            Message msg = new Message();
            msg.what = COMPLETED;
            handler.sendMessage(msg);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initAction() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            mWeiboDialog = DialogUtils.createLoadingDialog(VideoActivity.this, "加载中...");
            List<String> list = (List<String>) data.getSerializableExtra(PhotoSelectActivity.DATA);
            //获取当前时间
            String fileName = "/" + ImageUtils.getStringRandom(28);
            String filePath = "/sdcard/encryption/Video";
            File file = new File(filePath);
//判断文件夹是否存在，如果不存在就创建，否则不创建
            if (!file.exists()) {
                //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                file.mkdirs();
            }
            String oldPath = list.get(0);
            String newPath = filePath + fileName;
            ImageUtils.renameFile(oldPath, newPath);
            VideoFileBean fileNameBean = new VideoFileBean();
            fileNameBean.setIds(ids);
            fileNameBean.setName(filePath + fileName);
            fileNameBean.save();
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + oldPath)));
            ToastUtils.showShortToast("完成");
            new WorkThread().start();

        }
    }


}
